package opos;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.sql.*;

public class BuscaPregEx {

	ArrayList<Pregunta> todas_preguntas = new ArrayList<Pregunta>();
	ArrayList<String> enunciados = new ArrayList<String>();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BuscaPregEx busca = new BuscaPregEx();

		String dir_base = "H:/Users/antonio/Documents/personal/opos/preparaTIC";
		String dir_XIX = dir_base + "/PREPARATIC 2009/primero/tests/test 2010";
		String dir_XX = dir_base + "/PREPARATIC 2010 (XX)/primero/tests";

		try {
			String dirResult = "H:/Users/antonio/Documents/personal/opos/documentacion";
			FileWriter ficheroP = new FileWriter(dirResult + "/Result_preg.txt");
			PrintWriter pwP = new PrintWriter(ficheroP);
			FileWriter ficheroS = new FileWriter(dirResult + "/Result_sol.txt");
			PrintWriter pwS = new PrintWriter(ficheroS);

			String patron = "spice";
			String tema = "*";
			boolean soloEnPregunta = false;
			boolean soloEnExamen = true;
			boolean caseSensitive = false;
			boolean elim_repetidos = true;

//			patron = busca.parse(patron);
//			busca.almacena(dir_XX);

			// almacena toda la info en bbdd
			busca.almacena(dir_XIX);
			busca.almacenaEnBBDD("preguntasxix");
			busca.almacenaEnBBDD("todaspreg");
			busca.todas_preguntas.clear();
			busca.almacena(dir_XX);
			busca.almacenaEnBBDD("preguntasxx");
			busca.almacenaEnBBDD("todaspreg");
			//////////////////////////////////////////////////

//			 busca.buscaPregEx(patron, tema, pwP, pwS, soloEnPregunta, soloEnExamen, caseSensitive, elim_repetidos);
//
//			pwP.close();
//			pwS.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void almacena(String dataDir) throws Exception {
		File[] files = new File(dataDir).listFiles();

		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead() && f.getName().endsWith(".js")) {
				// System.out.println("Siguiente file["+f.getPath()+"\\"+f.getName());
				procesaFichero(f);
			} else if (f.isDirectory()) {
				almacena(f.getAbsolutePath());
			}
		}

	}

	private void buscaPregEx(String patron, String temas, PrintWriter pwP, PrintWriter pwS, boolean soloPregunta, boolean soloEnExamen, boolean caseSensitive,
			boolean elim_repetidos) {

		// if (soloPregunta) {
		// for (Pregunta p : todas_preguntas) {
		// if (p.tieneEnPregunta(patron, caseSensitive) && p.esTema(temas) &&
		// p.esDeExamen(soloEnExamen) && !esta(p)) {
		// // System.out.println(p.toStringFormat());
		// pwP.println(p.toStringFormat(false));
		// pwS.println(p.toStringFormat(true));
		// }
		// }
		// } else {
		// for (Pregunta p : todas_preguntas) {
		// if (p.tiene(patron, caseSensitive) && p.esTema(temas) &&
		// p.esDeExamen(soloEnExamen) && !esta(p)) {
		// // System.out.println(p.toStringFormat());
		// pwP.println(p.toStringFormat(false));
		// pwS.println(p.toStringFormat(true));
		// }
		// }
		// }
		for (Pregunta p : todas_preguntas) {
			if (elim_repetidos && esta(p)) {
				continue;
			}
			if (soloPregunta && !p.tieneEnPregunta(patron, caseSensitive)) {
				continue;
			}
			if (p.tiene(patron, caseSensitive) && p.esTema(temas) && p.esDeExamen(soloEnExamen)) {
				// System.out.println(p.toStringFormat());
				pwP.println(p.toStringFormat(false));
				pwS.println(p.toStringFormat(true));
			}
		}
	}

	private void procesaFichero(File f) throws Exception {
		// System.out.println("procesa fichero:"+f.getName());
		FileReader fr = new FileReader(f);
		BufferedReader br = new BufferedReader(fr);

		String linea;
		String datosPregunta;
		while ((linea = br.readLine()) != null) {
			// if ((linea.indexOf("questions[") != -1) &&
			// (linea.indexOf("document.writeln") == -1)) {
			if (linea.indexOf("Id pregunta:") != -1) {
				datosPregunta = linea;
				linea = br.readLine();
				if ((linea.indexOf("questions[") != -1) && (linea.indexOf("document.writeln") == -1) && linea.length() > 27) {
					br.readLine();// nos saltamos una
					Pregunta p = new Pregunta(f.getName(), parse(linea), parse(br.readLine()), parse(br.readLine()), parse(br.readLine()), parse(br.readLine()),
							parse(br.readLine()), parse(br.readLine()), parse(br.readLine()), parseDatosPreg(datosPregunta, "num"), parseDatosPreg(datosPregunta, "a�o"));
					// System.out.println(p);
					this.todas_preguntas.add(p);
				}
			}

		}
	}

	public String parse(String s) {
		return s.replace("&ntilde;", "�").replace("&Ntilde;", "�").replace("&aacute;", "�").replace("&eacute;", "�").replace("&iacute;", "�").replace("&oacute;", "�")
				.replace("&uacute;", "�").replace("&iquest;", "�").replace("&ldquo;", "'").replace("&rdquo;", "'").replace("&ndash;", "-").replace("&quot;", "'")
				.replace("&lsquo;", "'").replace("&rsquo;", "'").replace("&Iacute;", "�").replace("&Aacute;", "�").replace("&Eacute;", "�").replace("&euro;", "�")
				.replace("&Uacute;", "�");
	}

	private String parseDatosPreg(String datosPreg, String dato) {
		// Formato ejemplo
		// "//  Id pregunta: 557 Año de creación de pregunta: 2004-01-01"
		String[] d = datosPreg.split(" ");

		String result;
		if (dato.equalsIgnoreCase("num")) {
			result = d[4];
		} else {
			// a�o de la pregunta
			result = d[10];
			result = result.substring(0, result.indexOf("-"));
		}

		return result;
	}

	// para no incluir preguntas repetidas
	private boolean esta(Pregunta p) {
		String e = p.getQuestion();
		e = Utils.clean3(e);
		for (String en : enunciados) {
			if (e.equalsIgnoreCase(en))
				return true;
		}
		enunciados.add(e);
		return false;
	}

	/**************************************************************************************************************************************************
	 * 
	 * Almacenamiento en BBDD
	 * 
	 **************************************************************************************************************************************************/

	private Connection connectBBDD() {
		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/";
		
		String dbName = "opos";
		String driver = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "antonio";
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url + dbName, userName, password);
			System.out.println("Connected to the database");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return conn;
	}

	private void disconnectBBDD(Connection conn) {
		try {
			conn.close();
			System.out.println("Disconnected from database");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void almacenaEnBBDD(String tabla) {
		Connection conn = connectBBDD();

		String insert = "INSERT INTO " + tabla + "(num_preg,a�o_preg,enunciado,respuesta_0,respuesta_1,respuesta_2,respuesta_3,solucion,comentarios,temas,fichero,preg_entera) "
				+ " values (?,?,?,?,?,?,?,?,?,?,?,?)";

		try {
			PreparedStatement prest = conn.prepareStatement(insert);
			for (Pregunta p : todas_preguntas) {

				// System.out.println(p);

				prest.setInt(1, p.numPregunta);
				prest.setInt(2, p.anoPregunta);
				prest.setString(3, Utils.clean2(p.question));
				prest.setString(4, Utils.clean(p.choice1));
				prest.setString(5, Utils.clean(p.choice2));
				prest.setString(6, Utils.clean(p.choice3));
				prest.setString(7, Utils.clean(p.choice4));
				prest.setString(8, Utils.cleanSolucion(p.answer));

				prest.setString(9, Utils.clean2(p.comments));
				prest.setString(10, Utils.clean2(p.units));
				prest.setString(11, p.fichero);
				prest.setString(12, p.toStringFormat(true));

				prest.executeUpdate();
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			disconnectBBDD(conn);
		}

	}

	/**************************************************************************************************************************************************
	 * 
	 *
	 **************************************************************************************************************************************************/
	class Pregunta {
		String fichero;
		String question;
		String choice1;
		String choice2;
		String choice3;
		String choice4;
		String answer;
		String units;
		String comments;
		int numPregunta;
		int anoPregunta;

		public Pregunta(String fichero, String q, String c1, String c2, String c3, String c4, String ans, String u, String c, String numP, String anoP) {

			this.fichero = fichero;
			this.question = q;
			this.choice1 = c1;
			this.choice2 = c2;
			this.choice3 = c3;
			this.choice4 = c4;
			this.answer = ans;
			this.units = u;
			this.comments = c;

			numPregunta = Integer.parseInt(numP);
			anoPregunta = Integer.parseInt(anoP);
		}

		public String getQuestion() {
			return this.question;
		}

		public boolean esDeExamen(boolean esDeEx) {
			if (esDeEx)
				return comments.length() > 20;
			else
				return true;
		}

		public boolean tieneEnPregunta(String patron, boolean caseSensitive) {
			if (patron.equals("*"))
				return true;
			else {
				String[] p = patron.split(",");
				if (caseSensitive) {
					for (String s : p) {
						if (question.indexOf(s) != -1)
							return true;
					}
				} else {
					for (String s : p) {
						if (question.toLowerCase().indexOf(s.toLowerCase()) != -1)
							return true;
					}
				}
			}
			return false;

		}

		public boolean tiene(String patron, boolean caseSensitive) {
			if (patron.equals("*"))
				return true;
			else {
				String[] p = patron.split(",");
				if (caseSensitive) {
					for (String s : p) {
						if ((question.indexOf(s) != -1) || (choice1.indexOf(s) != -1) || (choice2.indexOf(s) != -1) || (choice3.indexOf(s) != -1) || (choice4.indexOf(s) != -1))
							return true;
					}
				} else {
					for (String s : p) {
						if ((question.toLowerCase().indexOf(s.toLowerCase()) != -1) || (choice1.toLowerCase().indexOf(s.toLowerCase()) != -1)
								|| (choice2.toLowerCase().indexOf(s.toLowerCase()) != -1) || (choice3.toLowerCase().indexOf(s.toLowerCase()) != -1)
								|| (choice4.toLowerCase().indexOf(s.toLowerCase()) != -1))
							return true;
					}
				}
			}
			return false;

		}

		public boolean esTema(String tema) {
			if (tema.equals("*"))
				return true;
			else {
				String[] sp = tema.split(",");
				for (String s : sp) {
					if (units.indexOf(s, 10) != -1)
						return true;
				}
				return false;
			}
		}

		public String toString() {
			return "Pregunta[" + question + "] c1[" + choice1 + "] c2[" + choice2 + "] c3[" + choice3 + "] c4[" + choice4 + "] answer[" + answer + "] units[" + units
					+ "] comments[" + comments + "] fichero[" + fichero + "]";
		}

		public String toStringFormat(boolean conSolucion) {
			// formato notepad++
			// return fichero + "\n" + question + "\n\t" + choice1 + "\n\t" +
			// choice2 + "\n\t" + choice3 + "\n\t" + choice4 + "\n\t" + answer +
			// "\n\t" + units + "\n\t" + comments
			// + "\n";

			if (conSolucion) {
				return fichero + " / " + Utils.clean2(comments) + " / " + units + "\n" + Utils.clean2(question) + "\n\t" + Utils.clean(choice1) + "\n\t" + Utils.clean(choice2)
						+ "\n\t" + Utils.clean(choice3) + "\n\t" + Utils.clean(choice4) + "\n\t" + Utils.clean(answer) + "\n";
			} else {
				return fichero + " / " + Utils.clean2(comments) + " / " + units + "\n" + Utils.clean2(question) + "\n\t" + Utils.clean(choice1) + "\n\t" + Utils.clean(choice2)
						+ "\n\t" + Utils.clean(choice3) + "\n\t" + Utils.clean(choice4) + "\n";
			}

		}

	}
}
